package mya.mes.mdc.logic.dispatch.executor;

import mya.common.jpa.JPAUtils;
import mya.common.jpa.context.NoLoginLogic;
import mya.common.jpa.context.ServiceContext;
import mya.mes.mdc.local.mongodb.OperateConstant;
import mya.mes.mdc.logic.alarm.build.AlarmSentSaver;
import mya.mes.mdc.logic.alarm.build.CurrentAlarm;
import mya.mes.mdc.logic.dispatch.build.SendAlarmContentVoBuilder;
import mya.mes.mdc.model.alarm.Alarm;
import mya.mes.mdc.model.dispatch.MdcDispatchContent;
import mya.mes.mdc.weixin.WxUploadManager;

import java.util.List;
import java.util.UUID;

/**
 * 定期发送报警消息<br>
 * 通过定期的方式，而不是实时的方式，确保发送之间有一定的时间间隔，确保消息发送成功???
 */
public class SendAlarmTimerTask implements Runnable {
    private volatile MdcDispatchContent dispatchContent = null;
    @Override
    public void run() {
        try {
            List<Alarm> listStart = CurrentAlarm.getInstance().sentToWeixinList();
            List<Alarm> managerList = CurrentAlarm.getInstance().sentToManagerList();
            List<Alarm> stopList = CurrentAlarm.queue.take();
            if ((listStart == null || listStart.isEmpty()) &&
                    (managerList == null || managerList.isEmpty())) {
                return;
            }
            String id = UUID.randomUUID().toString().replace("-","");
            String send = SendAlarmContentVoBuilder.build(id,listStart,stopList,managerList);
            SendAlarmContentVoBuilder.saveSendMiNi(OperateConstant.before,id,listStart,stopList,managerList);
            WxUploadManager.getInstance().publish(send);
            SendAlarmContentVoBuilder.saveSendMiNi(OperateConstant.ok,id,listStart,stopList,managerList);
            AlarmSentSaver.updateAlarmCurrent(listStart,managerList);
            AlarmSentSaver.updateAlarm(listStart,managerList);
            AlarmSentSaver.updateStopAlarm(stopList);
        } catch (Throwable ex) {
            System.out.println("===================MQTT远程发送失败===================" );
            ex.printStackTrace();
            return;
        }
        System.out.println("===================MQTT远程发送成功===================");
    }


    public MdcDispatchContent delete(Long contentId) throws Exception {

        NoLoginLogic logic = new NoLoginLogic(JPAUtils.DEFAULT_TENANT_ID) {
            @Override
            protected Object process(ServiceContext context) throws Exception {
                MdcDispatchContent content = context.em.find(MdcDispatchContent.class, contentId);
                if (content == null) {
                    return null;
                }
                context.em.remove(content);
                return content;
            }
        };

        return (MdcDispatchContent) logic.callLogic();
    }
}
